package com.firefly.service.command.ums;

import com.firefly.dao.dao.ums.po.DepartmentPo;
import com.firefly.dao.assembler.ums.DepartmentAssembler;
import com.firefly.util.handle.FireflyException;
import com.firefly.dao.dto.ums.DepartmentDto;
import com.firefly.dao.dto.ums.DepartmentRemoveAdminDto;
import com.firefly.dao.dto.ums.DepartmentStatusDto;
import com.firefly.service.repository.ums.DepartmentAdminRepository;
import com.firefly.service.repository.ums.DepartmentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @description: 部门领域服务
 * @author: lzg(萤火科技 ： 854378082 @ qq.com)
 * @date: 2022/11/30
 **/
@Service
public class DepartmentCommand {
    private final DepartmentRepository departmentRepository;
    private final DepartmentAdminRepository departmentAdminRepository;
    private final DepartmentAssembler departmentAssembler;
    @Autowired
    public DepartmentCommand(DepartmentRepository departmentRepository, DepartmentAdminRepository departmentAdminRepository, DepartmentAssembler departmentAssembler){
        this.departmentRepository = departmentRepository;
        this.departmentAdminRepository = departmentAdminRepository;
        this.departmentAssembler = departmentAssembler;
    }
    public boolean create(DepartmentDto request){
        DepartmentPo entity = departmentAssembler.getPo(request);
        return departmentRepository.createEntity(entity);
    }
    public boolean update(DepartmentDto request){
        if (request.getId() == request.getParentId()){
            throw new FireflyException(403,"父级不能选择自己");
		}
        DepartmentPo entity = departmentAssembler.getPo(request);
        return departmentRepository.updateById(entity);
    }
    public boolean changeStatus(DepartmentStatusDto request){
        DepartmentPo entity = departmentAssembler.getPo(request);
        return departmentRepository.changeStatusById(entity);
    }
    public boolean removeById(Integer id){
        List<Integer> ids = departmentRepository.getIds(id);
        // 查有没有用户
        Long count = departmentAdminRepository.getUserNum(ids);
        if (count > 0) {
            throw new FireflyException(403, "确认所有部门下没有用户才可以删除");
        }
        return departmentRepository.removeId(ids);
    }
    public boolean removeAdmin(DepartmentRemoveAdminDto request){
        return departmentRepository.removeAdmin(request.getId(),request.getAdminId());
    }
}
